/**
 * 图片处理路由
 * @module routes/image
 */

const express = require('express');
const router = express.Router();
const multer = require('multer');
const path = require('path');
const fs = require('fs');
const imageController = require('../controllers/image.controller');
const authMiddleware = require('../middlewares/auth.middleware');
const config = require('../config/config');

// 确保临时上传目录存在
const tmpDir = path.join(process.cwd(), 'tmp');
if (!fs.existsSync(tmpDir)) {
  fs.mkdirSync(tmpDir, { recursive: true });
}

// 配置multer存储
const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, tmpDir);
  },
  filename: (req, file, cb) => {
    const uniqueSuffix = `${Date.now()}-${Math.round(Math.random() * 1E9)}`;
    cb(null, `${file.fieldname}-${uniqueSuffix}${path.extname(file.originalname)}`);
  }
});

// 创建multer上传中间件
const upload = multer({
  storage,
  limits: {
    fileSize: 5 * 1024 * 1024, // 默认限制5MB（免费用户）
  },
  fileFilter: (req, file, cb) => {
    // 验证文件类型
    const filetypes = /jpeg|jpg|png|gif|webp|svg/;
    const mimetype = filetypes.test(file.mimetype);
    const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
    
    if (mimetype && extname) {
      return cb(null, true);
    }
    
    cb(new Error('只支持图片文件 (jpeg, jpg, png, gif, webp, svg)'));
  }
});

// 所有路由都需要认证
router.use(authMiddleware.authenticate);

// 图片压缩
router.post('/compress', upload.single('file'), imageController.compressImage);

// 批量图片压缩
router.post('/compress-batch', upload.array('files', 10), imageController.compressBatch);

// 图片格式转换
router.post('/convert', upload.single('file'), imageController.convertImage);

// 图片裁剪
router.post('/crop', upload.single('file'), imageController.cropImage);

// 图片旋转和翻转
router.post('/rotate', upload.single('file'), imageController.rotateImage);

// 添加水印
// 使用特殊的multer配置处理多个文件字段
const watermarkUpload = multer({
  storage,
  limits: {
    fileSize: 5 * 1024 * 1024 // 默认限制5MB（免费用户）
  },
  fileFilter: (req, file, cb) => {
    // 验证文件类型
    const filetypes = /jpeg|jpg|png|gif|webp|svg/;
    const mimetype = filetypes.test(file.mimetype);
    const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
    
    if (mimetype && extname) {
      return cb(null, true);
    }
    
    cb(new Error('只支持图片文件 (jpeg, jpg, png, gif, webp, svg)'));
  }
}).fields([
  { name: 'file', maxCount: 1 },
  { name: 'watermarkImage', maxCount: 1 }
]);

router.post('/watermark', watermarkUpload, imageController.addWatermark);

// 动态设置文件大小限制的中间件
router.use((req, res, next) => {
  // 如果用户是专业版会员，调整文件大小限制
  if (req.user && req.user.isPro) {
    upload.limits.fileSize = 50 * 1024 * 1024; // 50MB
  } else {
    upload.limits.fileSize = 5 * 1024 * 1024; // 5MB
  }
  next();
});

module.exports = router; 